package com.detrum.costomview;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.detrum.base.R;
import com.detrum.bean.ViewPagerItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by abc on 2017/7/24.
 */

public class MyViewPager extends RelativeLayout {
    private Context context;
    private View view;
    private ViewPager vp_banner;
    private LinearLayout banner_points;
    private List<ViewPagerItem> list;
    private List<MyViewPagerItem> list_iv;
    private ImagePagerAdapter imagePagerAdapter;
    private MyViewPagerCall myViewPagerCall;
    private int flag;
    private int index;
    private int Time = 5000;
    private boolean isStart;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //Log.i("MyBanner","index==r=="+index);
            index++;
            vp_banner.setCurrentItem(index);
            //Log.i("MyBanner","isStart=="+isStart);
            if (isStart) {
                handler.postDelayed(runnable, Time);
            }
        }
    };

    public MyViewPager(Context context) {
        super(context);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.myviewpager, this, true);
        init();
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.myviewpager, this, true);
        init();

    }


    public void init() {
        vp_banner = (ViewPager) view.findViewById(R.id.vp_banner);
        banner_points = (LinearLayout) view.findViewById(R.id.banner_points);
        list_iv = new ArrayList<>();
        imagePagerAdapter = new ImagePagerAdapter();
        vp_banner.setAdapter(imagePagerAdapter);
        vp_banner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(myViewPagerCall!=null){
                    myViewPagerCall.SelectItem(position);
                }
                index = position;
                for (int i = 0; i < list.size(); i++) {
                    ((ImageView) banner_points.getChildAt(i)).setImageResource(R.mipmap.point_h);
                }
                if (position == 0) {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point_s);
                } else {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point_s);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void setMyViewPagerCall(MyViewPagerCall myViewPagerCall) {
        this.myViewPagerCall = myViewPagerCall;
    }

    public void setList(List<ViewPagerItem> list) {
        if(this.list!=null){
            this.list.clear();
        }else{
            this.list=new ArrayList<>();
        }
        this.list.addAll(list);
        init();
        AddContent();
        imagePagerAdapter=null;
        imagePagerAdapter=new ImagePagerAdapter();
        vp_banner.setAdapter(imagePagerAdapter);
        //vp_banner.setCurrentItem(0);
    }

    public void start() {
        isStart = true;
        handler.postDelayed(runnable, Time);
    }

    public void stop() {
        isStart = false;
    }

    public int getItem(){
       return vp_banner.getCurrentItem();
    }

    public void setItem(int position){
        vp_banner.setCurrentItem(position);
    }

    public void UpData(List<ViewPagerItem> list, int id) {
        if(this.list!=null){
            this.list.clear();
        }else{
            this.list=new ArrayList<>();
        }
        this.list.addAll(list);
        AddContent();
        imagePagerAdapter=null;
        imagePagerAdapter=new ImagePagerAdapter();
        vp_banner.setAdapter(imagePagerAdapter);
        vp_banner.setCurrentItem(id);
    }

    /**
     * 往list_iv中添加数据
     */
    private void AddContent() {
        if (list.size() != 0) {
            //加载本地数据
            list_iv.clear();
            for (int i = 0; i < list.size(); i++) {
                MyViewPagerItem myViewPagerItem=new MyViewPagerItem(context);
                myViewPagerItem.setData(list.get(i));
                list_iv.add(myViewPagerItem);
            }
            //加载小点
            banner_points.removeAllViews();
            for (int i = 0; i < list.size(); i++) {
                ImageView view = new ImageView(context);
                view.setScaleType(ImageView.ScaleType.CENTER);
                banner_points.addView(view);
                if (i == 0) {
                    view.setImageResource(R.mipmap.point_s);
                } else {
                    view.setImageResource(R.mipmap.point_h);
                }
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
                params.rightMargin = 10;
                params.width = 15;
                params.height = 15;
                view.setLayoutParams(params);
            }


        }else{
            banner_points.removeAllViews();
        }
    }

    class ImagePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            //此处如设置为Integer.Max则为无限循环展示
            return list==null?0:list.size();
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(final ViewGroup container, int position) {
            //改变位置使之在size之内
            // Log.i("MyViewPager","instantiateItem");
            ViewParent vp = null;
            if (list != null && list.size() != 0) {

                if(list_iv != null&&list_iv.size() != 0){
                    vp = list_iv.get(position).getParent();
                    //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
                    if (vp != null) {
                        ViewGroup parent = (ViewGroup) vp;
                        parent.removeView(list_iv.get(position));
                    }

                    container.addView(list_iv.get(position));
                    //添加监听点击事件
                    final int finalPosition = position;
                    list_iv.get(position).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            myViewPagerCall.onClick(view, finalPosition);
                        }
                    });
                    //Log.i("MyBanner","add===添加"+position);
                    return list_iv.get(position);
                }else{
                    return null;
                }

            } else {
                return null;
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //Log.i("MyViewPager","destroyItem");
            if (list != null && list.size() != 0) {
                if(list_iv!=null&&list_iv.size()!=0&&position<list_iv.size()){
                    container.removeView(list_iv.get(position));
                }

            }
        }

        @Override
        public void startUpdate(ViewGroup container) {
            super.startUpdate(container);
            //Log.i("MyViewPager","startUpdate");
            // Log.i("MyViewPager","count=="+container.getChildCount()+"\nid=="+container.getId());

        }

        @Override
        public void finishUpdate(ViewGroup container) {
            super.finishUpdate(container);
            // Log.i("MyViewPager","finishUpdate");
            // Log.i("MyViewPager","count=="+container.getChildCount()+"\nid=="+container.getId());
        }
    }
}
